package com.teradata.io.bio;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/14 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */

@Slf4j
public class Server {

    // 默认的端口号
    private static int DEFAULT_PORT = 7777;

    private static ServerSocket serverSocket;

    public static void start() throws IOException {
        start(DEFAULT_PORT);
    }

    private synchronized static void start(int defaultPort) throws IOException {
        if (serverSocket != null) return;

        try {
            serverSocket = new ServerSocket(defaultPort);
            //System.out.println("服务端已启动，端口号：" + defaultPort);
            log.info("服务端已启动，端口号：" + defaultPort);
            while(true) {
                Socket socket = serverSocket.accept();
                new Thread(new ServerHandler(socket)).start();
            }

        } finally {
            if (serverSocket != null) {
                //System.out.println("服务已关闭.");
                log.info("服务已关闭.");
                serverSocket.close();
                serverSocket = null;
            }
        }

    }


}
